﻿using Callisto.Controls;
using StudentLive.Common;
using StudentLive.DataModel;
using StudentLive.DataModel.HubGroups;
using StudentLive.InnerPages;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.IO;
using System.Linq;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.Storage;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

// The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=234238

namespace StudentLive
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class HubPage : StudentLive.Common.LayoutAwarePage
    {
        public HubPage()
        {
            this.InitializeComponent();
        }


        /// <summary>
        /// Populates the page with content passed during navigation.  Any saved state is also
        /// provided when recreating a page from a prior session.
        /// </summary>
        /// <param name="navigationParameter">The parameter value passed to
        /// <see cref="Frame.Navigate(Type, Object)"/> when this page was initially requested.
        /// </param>
        /// <param name="pageState">A dictionary of state preserved by this page during an earlier
        /// session.  This will be null the first time a page is visited.</param>
        protected override void LoadState(Object navigationParameter, Dictionary<String, Object> pageState)
        {
            //ObservableCollection<TopicItem> items = JsonSerializer.Deserialize<ObservableCollection<TopicItem>>(navigationParameter as string);
            //this.DefaultViewModel["Groups"] = items;
            //this.groupGridView.ItemsSource = items;


            // TODO: Create an appropriate data model for your problem domain to replace the sample data
            var items = LiveDataSource.GetHubGroups((String)navigationParameter);

            var localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
            this.DefaultViewModel["Groups"] = items;
            this.groupGridView.ItemsSource = items;

        }

        private void FavoriteButtonClick(object sender, RoutedEventArgs e)
        {
            var lr = ((ResourceItem)(itemGridView.SelectedItem));
            lr.IsFavoured = !lr.IsFavoured;
            LiveDataSource.UpdateLearningResource(lr);
            if (!lr.IsFavoured)           
            {
                UnFavorButton.Visibility = Visibility.Collapsed;
                this.DefaultViewModel["Groups"] = LiveDataSource.GetHubGroups("AllGroups");
            }
            BottomAppBar.IsOpen = false;
            BottomAppBar.Visibility = Visibility.Collapsed;

        }


        private void ItemView_ItemClick(object sender, ItemClickEventArgs e)
        {
            if (e.ClickedItem.GetType() == typeof(ResourceItem))
            {
                // Open the file
                DefaultLaunch((e.ClickedItem as ResourceItem).LocalPath);
            }
            else if (e.ClickedItem.GetType() == typeof(SharedMaterialsItem))
            {
                StaticLaunch((e.ClickedItem as SharedMaterialsItem).LocalPath);
            }
            else if (e.ClickedItem.GetType() == typeof(CoursePlanItem))
            {
                // CALL UP THE PLAY VIDEO PAGE
                //var mailto = new Uri("mailto:?to=recipient@example.com&subject=The subject of an email&body=Hello from a Windows 8 Metro app.");
                //await Windows.System.Launcher.LaunchUriAsync(mailto);
                this.Frame.Navigate(typeof(LessonDetails), (e.ClickedItem as CoursePlanItem).CoursePlanID);
            }
            else if (e.ClickedItem.GetType() == typeof(StudentItem) || e.ClickedItem.GetType() == typeof(TeacherItem))
            {
                StudentCard std = new StudentCard();
                std.DataContext = e.ClickedItem;

                //TODO: Flyouts in students
                //Flyout f = new Flyout();
                //f.Placement = PlacementMode.Bottom;
                //f.PlacementTarget = sender as UIElement; // this is an UI element (usually the sender)
                //f.Content = std;
                //f.Height = 300; f.Width = 400;
                //f.VerticalOffset = Window.Current.Bounds.Height / 2 - f.Height / 2;

                //f.Background = new SolidColorBrush(Windows.UI.Colors.White);

                //f.IsOpen = true;
            }
        }

        private void Header_Click(object sender, RoutedEventArgs e)
        {
            var group = (sender as FrameworkElement).DataContext;
            HubGroup groupSelected = (group as HubGroup);

            if (groupSelected != null)
            {
                JumpToGroupDetails(groupSelected);
            }
        }

        private void groupTitle_Pressed(object sender, PointerRoutedEventArgs e)
        {
            var group = (e.OriginalSource as FrameworkElement).DataContext;
            HubGroup groupSelected = (group as HubGroup);

            if (groupSelected != null)
            {
                JumpToGroupDetails(groupSelected);
            }
        }

        private void groupTitle_Click(object sender, ItemClickEventArgs e)
        {
            HubGroup groupSelected = (e.ClickedItem as HubGroup);

            if (groupSelected != null)
            {
                JumpToGroupDetails(groupSelected);
            }
        }

        void JumpToGroupDetails(HubGroup groupSelected)
        {
            if (groupSelected is LessonPlans)
            {
                //TODO: Commented by Eduardo
                //this.Frame.Navigate(typeof(LessonPlanPage), "AllLessonPlans");
            }
            else if (groupSelected is Favorites)
            {
                //TODO: Commented by Eduardo
                //this.Frame.Navigate(typeof(FavoritesPage), "AllFavorites");
            }
            else if (groupSelected is Notifications)
            {
                this.Frame.Navigate(typeof(NotificationsPage), "AllNotifications");
            }
            else if (groupSelected is SharedMaterials)
            {
                this.Frame.Navigate(typeof(SharedMaterialsPage), "AllSharedMaterials");
            }
            else if (groupSelected is Students)
            {
                this.Frame.Navigate(typeof(StudentsPage), "AllStudents");
            }
            else if (groupSelected is Teachers)
            {
                this.Frame.Navigate(typeof(TeachersPage), "AllTeachers");
            }

        }

        #region UI Updates

        private void HubScrollViewer_ViewChanged(object sender, ScrollViewerViewChangedEventArgs e)
        {
            // Such a genius .. samples on google .

            //Thickness marginThickness = backgroundImage.Margin;

            //marginThickness.Left = (sender as ScrollViewer).HorizontalOffset * -0.10;

            //backgroundImage.Margin = marginThickness;
        }

        #endregion

        

        async void DefaultLaunch(string path)
        {
            // Path to the file in the app package to launch

            var file = await StorageFile.GetFileFromPathAsync(Path.Combine(Windows.Storage.ApplicationData.Current.LocalFolder.Path, path));

            if (file != null)
            {
                // Set the option to show the picker
                //var options = new Windows.System.LauncherOptions();
                //options.DisplayApplicationPicker = true;

                // Launch the retrieved file
                bool success = await Windows.System.Launcher.LaunchFileAsync(file);
                if (success)
                {
                    // File launched
                }
                else
                {
                    // File launch failed
                }
            }
            else
            {
                // Could not find file
            }
        }

        async void StaticLaunch(string path)
        {
            // Path to the file in the app package to launch

            Uri uri = new Uri(new Uri("ms-appx:///"), path);
            var file = await StorageFile.GetFileFromApplicationUriAsync(uri);

            if (file != null)
            {
                // Set the option to show the picker
                //var options = new Windows.System.LauncherOptions();
                //options.DisplayApplicationPicker = true;

                // Launch the retrieved file
                bool success = await Windows.System.Launcher.LaunchFileAsync(file);
                if (success)
                {
                    // File launched
                }
                else
                {
                    // File launch failed
                }
            }
            else
            {
                // Could not find file
            }
        }

        private async void SendEmailButton_Click(object sender, RoutedEventArgs e)
        {
            var user = (dynamic)itemGridView.SelectedItem;
            string address = user.Email;
            string body = string.Format("\n\n\n\n\nSent By LearN’Go.");
            var mailto = new Uri(string.Format("mailto:?to={0}&body={1}", address, body));
            await Windows.System.Launcher.LaunchUriAsync(mailto);
        }

        private void itemGridView_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            var item = itemGridView.SelectedItem;
            if (item != null)
            {
                if (item.GetType() == typeof(ResourceItem))
                {
                    BottomAppBar.IsOpen = true;
                    BottomAppBar.Visibility = Visibility.Visible;
                    SendMail.Visibility = Visibility.Collapsed;
                    var resourceItem = (ResourceItem)item;
                    if (resourceItem.IsFavoured)
                    {
                        UnFavorButton.Visibility = Visibility.Visible;
                    }
                }
                else if (item.GetType() == typeof(StudentItem) || item.GetType() == typeof(TeacherItem))
                {
                    BottomAppBar.IsOpen = true;
                    BottomAppBar.Visibility = Visibility.Visible;
                    UnFavorButton.Visibility = Visibility.Collapsed;
                    SendMail.Visibility = Visibility.Visible;
                }
                else
                {
                    BottomAppBar.Visibility = Visibility.Collapsed;
                    itemGridView.SelectedIndex = -1;
                }
            }
            else
            {
                BottomAppBar.Visibility = Visibility.Collapsed;
                itemGridView.SelectedIndex = -1;
            }
        }

    }
}
